﻿using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Audio;
using Microsoft.Xna.Framework.Content;

namespace Game500.Client
{
  public class SoundManager
  {
    private const float FadeLength = 1;
    private const float MaxPitch = 1.0f;
    private const float MinPitch = -1.0f;
    private readonly SoundEffectInstance myEngineSoundInstance;
    private readonly SoundEffectInstance myFireSoundInstance;
    private readonly SoundEffectInstance myIdleEngineSoundInstance;


    public SoundManager(ContentManager contentManager)
    {
      myIdleEngineSoundInstance = contentManager.Load<SoundEffect>("allison_1500").CreateInstance();
      myEngineSoundInstance = contentManager.Load<SoundEffect>("allison_2700").CreateInstance();
      myFireSoundInstance = contentManager.Load<SoundEffect>("air_can_02i").CreateInstance();

      myIdleEngineSoundInstance.IsLooped = true;

      myEngineSoundInstance.IsLooped = true;
    }

    public bool Boost { get; set; }

    public void Update(GameTime gameTime)
    {
      var time = (float)gameTime.ElapsedGameTime.TotalSeconds;
      if (Boost)
      {
        FadeDown(myIdleEngineSoundInstance, time, 0.0f, MaxPitch);
        FadeUp(myEngineSoundInstance, time, MinPitch, 0.0f);
      }
      else
      {
        FadeDown(myEngineSoundInstance, time, MinPitch, 0.0f);
        FadeUp(myIdleEngineSoundInstance, time, 0.0f, MaxPitch);
      }
    }

    private void FadeUp(SoundEffectInstance sound, float time, float minPitch, float maxPitch)
    {
      if (sound.State != SoundState.Playing) sound.Play();
      sound.Volume = MathHelper.Clamp(sound.Volume + Delta(time), 0.0f, 1.0f);
      if (minPitch == 0.0f) sound.Pitch = MathHelper.Clamp(sound.Pitch - Delta(time), minPitch, maxPitch);
      else sound.Pitch = MathHelper.Clamp(sound.Pitch + Delta(time), minPitch, maxPitch);
    }

    private void FadeDown(SoundEffectInstance sound, float time, float minPitch, float maxPitch)
    {
      sound.Volume = MathHelper.Clamp(sound.Volume - Delta(time), 0.0f, 1.0f);
      if (minPitch == 0.0f) sound.Pitch = MathHelper.Clamp(sound.Pitch + Delta(time), minPitch, maxPitch);
      else sound.Pitch = MathHelper.Clamp(sound.Pitch - Delta(time), minPitch, maxPitch);
    }

    private static float Delta(float time)
    {
      return 1.0f / (FadeLength / time);
    }

    public void Fire()
    {
      myFireSoundInstance.Play();
    }
  }
}